package com.villaday.idf.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Environment;

import androidx.annotation.IdRes;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.widget.NestedScrollView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.adapter.BournFiltersSortAdapter;
import com.villaday.idf.adapter.BournFiltersTypeAdapter;
import com.villaday.idf.adapter.CommentsAdapter;
import com.villaday.idf.adapter2.FindMinSulAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.BaseNoWhiteActivity;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.CustomPopupWindow;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.custom.RangeSeekBar.OnRangeChangedListener;
import com.villaday.idf.custom.RangeSeekBar.RangeSeekBar;
import com.villaday.idf.custom.pop.ShareActivityPop;
import com.villaday.idf.model.Houses_filtersEntity;
import com.villaday.idf.model.VillagesEntity;
import com.villaday.idf.model.Villages_commentsEntity;
import com.villaday.idf.model2.Find_House_minsu_listEntity;
import com.villaday.idf.model3.AllPostersEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtils;
import com.villaday.idf.util.ShareUtilse;
import com.villaday.idf.util.StatusBarUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.Utils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

import byc.imagewatcher.ImageWatcher;
import byc.imagewatcher.MessagePicturesLayout;
import io.reactivex.functions.Consumer;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

/*
 * 目的地详情列表
 * */
public class BourbonListActivity extends BaseNoWhiteActivity implements OkHttpUtil.OnDataListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, MessagePicturesLayout.Callback, ImageWatcher.OnPictureLongPressListener, BaseDialog.OnItemClickListener {


    @BindView(R.id.sdv)
    ImageView sdv;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.tv_default)
    TextView tvDefault;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_more)
    TextView tvMore;

    @BindView(R.id.tv_addr)
    TextView tvAddr;
    @BindView(R.id.tv_des)
    TextView tvDes;
    @BindView(R.id.tv_title)
    TextView tvTitle;


    @BindView(R.id.toolbar_back)
    ImageButton toolbar_back;


    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.tv_h5)
    WebView tvH5;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rv_dataList)
    RecyclerView rvDataList;
    @BindView(R.id.rv_comments)
    RecyclerView rvComments;


    @BindView(R.id.nsv)
    NestedScrollView nsv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.activity_main_app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.ll_addrSort)
    View ll_addrSort;

    @BindView(R.id.rb_3)
    RadioButton rbPL;
    @BindView(R.id.rb_0)
    RadioButton rb0;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;


    @BindView(R.id.activity_main_coll_tool_bar)
    CollapsingToolbarLayout activityMainCollToolBar;
    @BindView(R.id.ll)
    LinearLayout ll;

    @BindView(R.id.img_xcx)
    ImageView img_xcx;


    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 10;

    private int pageNoComments = 1;
    private int nextIndexComments = 1;
    private int pageSizeComments = 10;

    private String villageId = "";//小区ID
    private String city = "";//城市名称(如:深圳)
    private String area = "";//区县名称(如:盐田区)
    private String types = "";//房源类型(0:别墅客栈,1:特色公寓,3:轰趴场馆,4:度假村,空值:全部)
    private String minPrice = "0";//最低价格
    private String maxPrice = "0";//最高价格
    private String minPeople = "0";//最低人数
    private String maxPeople = "0";//最高人数
    private String facilities = "";//设施选项(多项以逗号分隔)(如:泳池,温泉...)
    private String sortBy = "";//排序规则(price_asc:价格最高,price_desc:价格最低,空值:默认排序)
    private String scenicSpotId = "";
    private String businesId = "";
    private String stationId = "";
    private String subwayLineId = "";
    private String collegeId = "";

    private ImageWatcher vImageWatcher;
    private AllPostersEntity.BodyBean allPostersEntity;

    private int minPriceCurrent = 0;
    private int maxPriceCurrent = 0;

    private int onChangeminPriceCurrent = 0;
    private int onChangemaxPriceCurrent = 0;

    private int peoplesCurrent = 0;
    private int onChangePeoplesCurrent = 0;


    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();
    private VillagesEntity villagesEntity;

    private List<Find_House_minsu_listEntity.BodyEntity.ListEntity> data = new ArrayList();
    private List<Villages_commentsEntity.BodyEntity.ListEntity> dataComments = new ArrayList();

    private FindMinSulAdapter bournDeticalAdapter;
    private Houses_filtersEntity houses_filtersEntity;
    private int currentSortPosition = 0;// 默认排序
    private int currentTypePosition = 0;// 房源类型

    private BournFiltersSortAdapter bournFiltersSortAdapter;
    private BournFiltersTypeAdapter bournFiltersTypeAdapter;
    private RangeSeekBar sideBar;
    Set<Integer> facilitiespositionS = new HashSet<Integer>();//设备选中的position  集合
    private TagAdapter<Houses_filtersEntity.BodyEntity.FiltersEntity.FacilitiesEntity> tagAdapter;
    private TagFlowLayout idFlowlayout;
    private View currentView;
    private CommentsAdapter commentsAdapter;
    private StatusLayoutManager statusLayoutManager;
    private CustomPopupWindow popuSort;
    private CustomPopupWindow popuType;
    private CustomPopupWindow popuMore;


    @Override
    protected int getViewResId() {
        return R.layout.activity_bourbon_list;
    }

    @Override
    protected void init() {
        initSharePop();
        statusLayoutManager = setupDefaultStatusLayoutManager(srl, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");

                loadData();

            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (popuType != null && popuType.getPopupWindow() != null) {
                    popuType.getPopupWindow().dismiss();
                    popuType=null;

                }
                if (popuMore != null && popuMore.getPopupWindow() != null) {
                    popuMore.getPopupWindow().dismiss();
                    popuMore=null;
                }
                if (popuSort != null && popuSort.getPopupWindow() != null) {
                    popuSort.getPopupWindow().dismiss();
                    popuSort=null;
                }

                if (verticalOffset >= 0) {

                    srl.setEnabled(true);
                } else {
                    srl.setEnabled(false);
                }

                if (verticalOffset >= PhoneUtil.dp2px(BourbonListActivity.this, -110)) {
                    toolbar_back.setImageResource(R.drawable.public_back_white);
                    img_xcx.setImageResource(R.drawable.public_share);
                } else {
                    toolbar_back.setImageResource(R.drawable.toolbar_back);
                    img_xcx.setImageResource(R.drawable.detailspage_share);

                }
            }
        });
        srl.setOnRefreshListener(this);
       /* //透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }*/

        StatusBarUtil.setTranslucentForImageViewInFragment(this, null);
        StatusBarUtil.setLightMode(this);


        rg.setOnCheckedChangeListener(this);
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        villageId = getIntent().getStringExtra("villageId");
        city = getIntent().getStringExtra("city");
        area = getIntent().getStringExtra("area");


        rvComments.setLayoutManager(new LinearLayoutManager(this));
        commentsAdapter = new CommentsAdapter(this, new OnAdapterCallbackListener() {
            @Override
            public void onCallback() {
                if (nextIndexComments == pageNoComments + 1) {
                    pageNoComments++;
                    getCommentsList();
                }
            }
        }, null);
        commentsAdapter.setPictureClickCallback(this);

        rvComments.setAdapter(commentsAdapter);

        //   rvComments.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.primaryBg), PhoneUtil.dp2px(this, 1)));
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        commentsAdapter.setEmptyView(R.layout.empty_tips);
        commentsAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");


        rvDataList.setLayoutManager(new LinearLayoutManager(this));
        bournDeticalAdapter = new FindMinSulAdapter(this, this, this);
        rvDataList.setAdapter(bournDeticalAdapter);

       // rvDataList.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.primaryBg), PhoneUtil.dp2px(this, 1)));
        bournDeticalAdapter.setOnItemClickListener(this);
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        bournDeticalAdapter.setEmptyView(R.layout.empty_tips);
        bournDeticalAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");

    }

    @Override
    protected void loadData() {
        OkHttpUtil.getJSON(this, String.format(Constant.URL.villages, villageId), this);

        getHouseList();
        getCommentsList();
    }

    //获取评论
    private void getCommentsList() {
        Map<String, String> map = new HashMap<>();
        //map.put("villageId", villageId + "");

        map.put("pageNo", pageNoComments + "");
        map.put("pageSize", pageSizeComments + "");

        OkHttpUtil.getJSON(this, String.format(Constant.URL.villages_comments, villageId), map, this);

    }

    private void getHouseList() {
        //价格
        if (houses_filtersEntity != null &&
                houses_filtersEntity.getBody() != null &&
                houses_filtersEntity.getBody().getFilters() != null &&
                houses_filtersEntity.getBody().getFilters().getPrices() != null) {
            minPrice = houses_filtersEntity.getBody().getFilters().getPrices().get(minPriceCurrent).getName();

            if (maxPriceCurrent == houses_filtersEntity.getBody().getFilters().getPrices().size() - 1) {
                maxPrice = "0";

            } else {
                maxPrice = houses_filtersEntity.getBody().getFilters().getPrices().get(maxPriceCurrent).getName();


            }
        }
        //人数
        if (houses_filtersEntity != null &&
                houses_filtersEntity.getBody() != null &&
                houses_filtersEntity.getBody().getFilters() != null &&
                houses_filtersEntity.getBody().getFilters().getPeoples() != null) {
            minPeople = houses_filtersEntity.getBody().getFilters().getPeoples().get(peoplesCurrent).getId();


        }
        //人数
        if (houses_filtersEntity != null &&
                houses_filtersEntity.getBody() != null &&
                houses_filtersEntity.getBody().getFilters() != null &&
                houses_filtersEntity.getBody().getFilters().getFacilities() != null) {

            facilities = "";
            for (Integer str : facilitiespositionS) {
                facilities = facilities + houses_filtersEntity.getBody().getFilters().getFacilities().get(str).getId() + ",";
            }
            if (!TextUtils.isEmpty(facilities)) {
                facilities = facilities.substring(0, facilities.length() - 1);
            }
        }


        Map<String, String> map = new HashMap<>();
        map.put("villageId", villageId);
        map.put("city", city);
        map.put("area", area);
        map.put("types", types);
        map.put("minPrice", minPrice);
        map.put("maxPrice", maxPrice);
        map.put("minPeople", minPeople);
        map.put("maxPeople", maxPeople);
        map.put("facilities", facilities);
        map.put("sortBy", sortBy);

        map.put("scenicSpotId", scenicSpotId);
        map.put("businesId", businesId);
        map.put("stationId", stationId);
        map.put("subwayLineId", subwayLineId);
        map.put("collegeId", collegeId);


        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");

        OkHttpUtil.getJSON(this, Constant.URL.houses_list, map, this);

    }

    @OnClick({R.id.tv_default, R.id.tv_type, R.id.tv_more})
    public void onViewClicked(View view) {
        if (houses_filtersEntity == null || houses_filtersEntity.getBody() == null || !"200".equals(houses_filtersEntity.getCode())) {
            loadingDialog = LoadingDialog.newInstance("加载中");
            loadingDialog.show(getFragmentManager(), "loading");
            OkHttpUtil.getJSON(this, Constant.URL.houses_filters, this);
            currentView = view;

        } else {
            getMore(view);
        }

    }

    private void getMore(View view) {
        switch (view.getId()) {
            case R.id.tv_default: {//默认排序
                popuSort();

            }
                /*ChooseDefalutDialog chooseDefalutDialog = ChooseDefalutDialog.newInstance();
                chooseDefalutDialog.show(getFragmentManager());*/

            break;
            case R.id.tv_type: {//房源类型
                popuType();

            }
            break;
            case R.id.tv_more: {//更多筛选
                popuMore();


            }
            break;

        }


    }

    private void popuMore() {
       /* View mAppBarChildAt = appBarLayout.getChildAt(0);
        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
        mAppBarParams.setScrollFlags(0);*/

        if (popuType != null && popuType.getPopupWindow() != null) {
            popuType.getPopupWindow().dismiss();
            popuType = null;

        }
        if (popuSort != null && popuSort.getPopupWindow() != null) {
            popuSort.getPopupWindow().dismiss();
            popuSort = null;

        }
        if (popuMore != null && popuMore.getPopupWindow() != null) {
            popuMore.getPopupWindow().dismiss();
            popuMore = null;
            return;
        }

        tvMore.setSelected(true);
        popuMore = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setOutSideCancel(false)
                .setContext(this)
                .setActivity(this)
                .isBlur(true)
                .setRadius(5)
                .setContentView(R.layout.popu_choose_more)
                .setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                      /*  View mAppBarChildAt = appBarLayout.getChildAt(0);
                        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
                        mAppBarParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                        mAppBarChildAt.setLayoutParams(mAppBarParams);*/
                        tvMore.setSelected(false);
                    }
                })
                .builder();

        popuMore.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popuMore.dismiss();
                if (popuType != null && popuType.getPopupWindow() != null) {
                    popuType.getPopupWindow().dismiss();
                    popuType = null;

                }
                if (popuSort != null && popuSort.getPopupWindow() != null) {
                    popuSort.getPopupWindow().dismiss();
                    popuSort = null;

                }
                if (popuMore != null && popuMore.getPopupWindow() != null) {
                    popuMore.getPopupWindow().dismiss();
                    popuMore = null;
                }
            }
        });


        if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
            popuMore.showAsLaction(ll_addrSort, Gravity.BOTTOM, 0, 0);

            //价格
            sideBar = (RangeSeekBar) popuMore.getItemView(R.id.sideBar);
            sideBar.setTypeface(Typeface.DEFAULT_BOLD);
            sideBar.getLeftSeekBar().setTypeface(Typeface.DEFAULT_BOLD);
            sideBar.setOnRangeChangedListener(new OnRangeChangedListener() {
                @Override
                public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                    onChangeminPriceCurrent = (int) leftValue;
                    onChangemaxPriceCurrent = (int) rightValue;
                }

                @Override
                public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

                }

                @Override
                public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

                }
            });
            sideBar.setTickMarkNumber(houses_filtersEntity.getBody().getFilters().getPrices().size() - 1);
            final CharSequence[] tickMarkTextArray = new CharSequence[houses_filtersEntity.getBody().getFilters().getPrices().size()];
            sideBar.setRangeInterval(100f / (houses_filtersEntity.getBody().getFilters().getPrices().size() - 1));
            for (int i = 0; i < houses_filtersEntity.getBody().getFilters().getPrices().size(); i++) {
                tickMarkTextArray[i] = houses_filtersEntity.getBody().getFilters().getPrices().get(i).getName();
            }
            sideBar.setTickMarkTextArray(tickMarkTextArray);
            if (maxPriceCurrent == 0) {
                maxPriceCurrent = tickMarkTextArray.length - 1;
                onChangemaxPriceCurrent = maxPriceCurrent;

            }
            sideBar.setValue(minPriceCurrent, maxPriceCurrent);

            // 出行人数
            final TextView peoples = (TextView) popuMore.getItemView(R.id.tv_peoples);
            //重置按钮

            popuMore.getItemView(R.id.tv_reset).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    minPriceCurrent = 0;
                    maxPriceCurrent = tickMarkTextArray.length - 1;
                    peoplesCurrent = 0;
                    onChangePeoplesCurrent = 0;
                    facilitiespositionS.clear();
                    tagAdapter.setSelectedList(facilitiespositionS);
                    sideBar.setValue(minPriceCurrent, maxPriceCurrent);
                    peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(onChangePeoplesCurrent).getName());

                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getFragmentManager(), "loading");
                    onRefresh();
                    // builder2.dismiss();
                }
            });


            //确定按钮

            popuMore.getItemView(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    minPriceCurrent = onChangeminPriceCurrent;
                    maxPriceCurrent = onChangemaxPriceCurrent;
                    peoplesCurrent = onChangePeoplesCurrent;
                    facilitiespositionS.clear();
                    facilitiespositionS.addAll(idFlowlayout.getSelectedList());
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getFragmentManager(), "loading");
                    onRefresh();
                    popuMore.dismiss();
                    if (popuType != null && popuType.getPopupWindow() != null) {
                        popuType.getPopupWindow().dismiss();
                        popuType = null;

                    }
                    if (popuSort != null && popuSort.getPopupWindow() != null) {
                        popuSort.getPopupWindow().dismiss();
                        popuSort = null;

                    }
                    if (popuMore != null && popuMore.getPopupWindow() != null) {
                        popuMore.getPopupWindow().dismiss();
                        popuMore = null;
                    }

                }
            });

            peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(peoplesCurrent).getName());
            onChangePeoplesCurrent = peoplesCurrent;
            // 出行人数减
            popuMore.getItemView(R.id.img_minus).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onChangePeoplesCurrent == 0) {
                        onChangePeoplesCurrent = houses_filtersEntity.getBody().getFilters().getPeoples().size() - 1;

                    } else {
                        onChangePeoplesCurrent = onChangePeoplesCurrent - 1;

                    }
                    peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(onChangePeoplesCurrent).getName());

                }
            });
            // 出行人数加

            popuMore.getItemView(R.id.img_plus).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onChangePeoplesCurrent == houses_filtersEntity.getBody().getFilters().getPeoples().size() - 1) {
                        onChangePeoplesCurrent = 0;

                    } else {
                        onChangePeoplesCurrent = onChangePeoplesCurrent + 1;

                    }
                    peoples.setText(houses_filtersEntity.getBody().getFilters().getPeoples().get(onChangePeoplesCurrent).getName());

                }
            });

            //设施
            idFlowlayout = (TagFlowLayout) popuMore.getItemView(R.id.id_flowlayout);


            tagAdapter = new TagAdapter<Houses_filtersEntity.BodyEntity.FiltersEntity.FacilitiesEntity>(houses_filtersEntity.getBody().getFilters().getFacilities()) {
                @Override
                public View getView(FlowLayout parent, int position, Houses_filtersEntity.BodyEntity.FiltersEntity.FacilitiesEntity s) {
                    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.tv_20_have_sheshi,
                            idFlowlayout, false);
                    tv.setText(s.getName());

                    return tv;
                }
            };
            idFlowlayout.setAdapter(tagAdapter);
            if (facilitiespositionS.size() != 0) {

                tagAdapter.setSelectedList(facilitiespositionS);
            }


            idFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {

                    return true;
                }
            });
        }
    }

    private void popuType() {
     /*   View mAppBarChildAt = appBarLayout.getChildAt(0);
        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
        mAppBarParams.setScrollFlags(0);*/
        if (popuSort != null && popuSort.getPopupWindow() != null) {
            popuSort.getPopupWindow().dismiss();
            popuSort = null;

        }
        if (popuMore != null && popuMore.getPopupWindow() != null) {
            popuMore.getPopupWindow().dismiss();
            popuMore = null;

        }
        if (popuType != null && popuType.getPopupWindow() != null) {
            popuType.getPopupWindow().dismiss();
            popuType = null;
            return;
        }
        tvType.setSelected(true);
        popuType = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setOutSideCancel(false)
                .setContext(this)
                .setActivity(this)
                .isBlur(true)
                .setRadius(5)
                .setContentView(R.layout.popu_bourn_head_chose_addr_sort)
                .setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                       /* View mAppBarChildAt = appBarLayout.getChildAt(0);
                        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
                        mAppBarParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                        mAppBarChildAt.setLayoutParams(mAppBarParams);*/
                        tvType.setSelected(false);
                    }
                })
                .builder();

        popuType.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popuType.dismiss();
                if (popuType != null && popuType.getPopupWindow() != null) {
                    popuType.getPopupWindow().dismiss();
                    popuType = null;

                }
                if (popuSort != null && popuSort.getPopupWindow() != null) {
                    popuSort.getPopupWindow().dismiss();
                    popuSort = null;

                }
                if (popuMore != null && popuMore.getPopupWindow() != null) {
                    popuMore.getPopupWindow().dismiss();
                    popuMore = null;
                }
            }
        });


        popuType.showAsLaction(ll_addrSort, Gravity.BOTTOM, 0, 0);

        RecyclerView rvAddr = (RecyclerView) popuType.getItemView(R.id.rv_addr_sort);
        rvAddr.setLayoutManager(new LinearLayoutManager(this));
        if (bournFiltersTypeAdapter == null) {
            bournFiltersTypeAdapter = new BournFiltersTypeAdapter(this);

        }
        if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
            bournFiltersTypeAdapter.setData(houses_filtersEntity.getBody().getTypes());
        }
        rvAddr.setAdapter(bournFiltersTypeAdapter);
        houses_filtersEntity.getBody().getTypes().get(currentTypePosition).setCheck(true);

        rvAddr.addItemDecoration(new RVItemDecoration(LinearLayoutCompat.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.primaryBg), PhoneUtil.dp2px(this, 1)));
        bournFiltersTypeAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                popuType.dismiss();
                if (popuType != null && popuType.getPopupWindow() != null) {
                    popuType.getPopupWindow().dismiss();
                    popuType = null;

                }
                if (popuSort != null && popuSort.getPopupWindow() != null) {
                    popuSort.getPopupWindow().dismiss();
                    popuSort = null;

                }
                if (popuMore != null && popuMore.getPopupWindow() != null) {
                    popuMore.getPopupWindow().dismiss();
                    popuMore = null;
                }

                if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null) {
                    houses_filtersEntity.getBody().getTypes().get(position).setCheck(!houses_filtersEntity.getBody().getTypes().get(position).isCheck());

                    if (currentTypePosition != position) {
                        houses_filtersEntity.getBody().getTypes().get(currentTypePosition).setCheck(!houses_filtersEntity.getBody().getTypes().get(currentTypePosition).isCheck());

                    }
                    if (houses_filtersEntity.getBody().getTypes().get(position).isCheck()) {
                        types = houses_filtersEntity.getBody().getTypes().get(position).getId();

                        tvType.setText(houses_filtersEntity.getBody().getTypes().get(position).getName());
                        currentTypePosition = position;
                    } else {
                        tvType.setText("房源类型");

                        types = "";
                        currentTypePosition = 0;

                    }
                    bournFiltersTypeAdapter.notifyDataSetChanged();
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getFragmentManager(), "loading");
                    onRefresh();
                }

            }
        });
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        bournFiltersTypeAdapter.setEmptyView(R.layout.empty_tips);
        bournFiltersTypeAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
    }

    private void popuSort() {
       /* View mAppBarChildAt = appBarLayout.getChildAt(0);
        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
        mAppBarParams.setScrollFlags(0);*/
        if (popuType != null && popuType.getPopupWindow() != null) {
            popuType.getPopupWindow().dismiss();
            popuType = null;

        }
        if (popuMore != null && popuMore.getPopupWindow() != null) {
            popuMore.getPopupWindow().dismiss();
            popuMore = null;

        }
        if (popuSort != null && popuSort.getPopupWindow() != null) {
            popuSort.getPopupWindow().dismiss();
            popuSort = null;
            return;
        }
        tvDefault.setSelected(true);

        popuSort = new CustomPopupWindow.Builder().setheight(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setwidth(LinearLayoutCompat.LayoutParams.MATCH_PARENT)
                .setOutSideCancel(false)
                .setContext(this)
                .setActivity(this)
                .isBlur(true)
                .setRadius(5)
                .setContentView(R.layout.popu_bourn_head_chose_addr_sort)
                .setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        /*View mAppBarChildAt = appBarLayout.getChildAt(0);
                        AppBarLayout.LayoutParams mAppBarParams = (AppBarLayout.LayoutParams) mAppBarChildAt.getLayoutParams();
                        mAppBarParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
                        mAppBarChildAt.setLayoutParams(mAppBarParams);*/
                        tvDefault.setSelected(false);
                    }
                })
                .builder();

        popuSort.getItemView(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popuSort.dismiss();
                if (popuType != null && popuType.getPopupWindow() != null) {
                    popuType.getPopupWindow().dismiss();
                    popuType = null;

                }
                if (popuSort != null && popuSort.getPopupWindow() != null) {
                    popuSort.getPopupWindow().dismiss();
                    popuSort = null;

                }
                if (popuMore != null && popuMore.getPopupWindow() != null) {
                    popuMore.getPopupWindow().dismiss();
                    popuMore = null;
                }
            }
        });


        popuSort.showAsLaction(ll_addrSort, Gravity.BOTTOM, 0, 0);


        RecyclerView rvAddr = (RecyclerView) popuSort.getItemView(R.id.rv_addr_sort);
        rvAddr.setLayoutManager(new LinearLayoutManager(this));
        if (bournFiltersSortAdapter == null) {
            bournFiltersSortAdapter = new BournFiltersSortAdapter(this);

        }
        houses_filtersEntity.getBody().getSorts().get(currentSortPosition).setCheck(true);

        if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
            bournFiltersSortAdapter.setData(houses_filtersEntity.getBody().getSorts());
        }
        rvAddr.setAdapter(bournFiltersSortAdapter);

        rvAddr.addItemDecoration(new RVItemDecoration(LinearLayoutCompat.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.primaryBg), PhoneUtil.dp2px(this, 1)));
        bournFiltersSortAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                popuSort.dismiss();
                if (popuType != null && popuType.getPopupWindow() != null) {
                    popuType.getPopupWindow().dismiss();
                    popuType = null;

                }
                if (popuSort != null && popuSort.getPopupWindow() != null) {
                    popuSort.getPopupWindow().dismiss();
                    popuSort = null;

                }
                if (popuMore != null && popuMore.getPopupWindow() != null) {
                    popuMore.getPopupWindow().dismiss();
                    popuMore = null;
                }

                if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null) {
                    houses_filtersEntity.getBody().getSorts().get(position).setCheck(!houses_filtersEntity.getBody().getSorts().get(position).isCheck());

                    if (currentSortPosition != position) {
                        houses_filtersEntity.getBody().getSorts().get(currentSortPosition).setCheck(!houses_filtersEntity.getBody().getSorts().get(currentSortPosition).isCheck());

                    }
                    if (houses_filtersEntity.getBody().getSorts().get(position).isCheck()) {
                        sortBy = houses_filtersEntity.getBody().getSorts().get(position).getId();

                        tvDefault.setText(houses_filtersEntity.getBody().getSorts().get(position).getName());
                        currentSortPosition = position;
                    } else {
                        tvDefault.setText("默认排序");

                        sortBy = "";
                        currentSortPosition = 0;

                    }
                    bournFiltersSortAdapter.notifyDataSetChanged();
                    loadingDialog = LoadingDialog.newInstance("加载中");
                    loadingDialog.show(getFragmentManager(), "loading");
                    onRefresh();
                }

            }
        });
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        bournFiltersSortAdapter.setEmptyView(R.layout.empty_tips);
        bournFiltersSortAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
    }

    @OnClick({R.id.toolbar_back, R.id.img_xcx})
    public void onViewClicked2(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                onBackPressed();
                break;
            case R.id.img_xcx:
                shareXCX();
                break;
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {

            statusLayoutManager.showSuccessLayout();
        }
        if (String.format(Constant.URL.villages, villageId).equals(url)) {
            LogeUtil.e("villages", json);
            villagesEntity = gson.fromJson(json, VillagesEntity.class);
            if (villagesEntity.getBody() != null && "200".equals(villagesEntity.getCode())) {
                initView();
            }
        } else if (Constant.URL.houses_list.equals(url)) {
            dismissLoading();
            LogeUtil.e("houses_list", json);
            Find_House_minsu_listEntity houses_listEntity = gson.fromJson(json, Find_House_minsu_listEntity.class);
            removeLoadingItem();
            if (pageNo == 1) {
                data.clear();
            }

            if ("200".equals(houses_listEntity.getCode()) && houses_listEntity.getBody() != null) {
                data.addAll(houses_listEntity.getBody().getList());
                if (houses_listEntity.getBody().isHasNext()) {
                    data.add(new Find_House_minsu_listEntity.BodyEntity.ListEntity(1));
                    nextIndex = pageNo + 1;

                } else {
                    addBaseLine();
                }

            } else {
                addBaseLine();
            }
            bournDeticalAdapter.setData(data);
        } else if (Constant.URL.houses_filters.equals(url)) {
            dismissLoading();
            LogeUtil.e("houses_filters", json);
            houses_filtersEntity = gson.fromJson(json, Houses_filtersEntity.class);

            if (houses_filtersEntity != null && houses_filtersEntity.getBody() != null && "200".equals(houses_filtersEntity.getCode())) {
                getMore(currentView);

            }

        } else if (String.format(Constant.URL.villages_comments, villageId).equals(url)) {
            LogeUtil.e("villages_comments", json);
            Villages_commentsEntity villages_commentsEntity = gson.fromJson(json, Villages_commentsEntity.class);

            removeCommentsLoadingItem();
            if (pageNoComments == 1) {
                dataComments.clear();
            }

            if ("200".equals(villages_commentsEntity.getCode()) && villages_commentsEntity.getBody() != null) {
                dataComments.addAll(villages_commentsEntity.getBody().getList());
                if (villages_commentsEntity.getBody().isHasNext()) {
                    dataComments.add(new Villages_commentsEntity.BodyEntity.ListEntity(1));
                    nextIndexComments = pageNoComments + 1;

                } else {
                    addCommentsBaseLine();
                }

            } else {
                addCommentsBaseLine();
            }
            boolean isTranslucentStatus = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                       /* Window window = getActivity().getWindow();
                        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                        window.setStatusBarColor(Color.TRANSPARENT);
                        window.setNavigationBarColor(Color.TRANSPARENT);
                        isTranslucentStatus = true;*/
            }
            // 一般来讲， ImageWatcher 需要占据全屏的位置
// 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
// 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
//设置指示器（默认小白点）
//设置指示器颜色
// 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
//调用show方法前，请先调用setLoader 给ImageWatcher提供加载图片的实现
            vImageWatcher = ImageWatcher.Helper.with(this) // 一般来讲， ImageWatcher 需要占据全屏的位置
                    .setTranslucentStatus(!isTranslucentStatus ? Utils.calcStatusBarHeight(this) : 0) // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
                    .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                    .setHintMode(ImageWatcher.POINT)//设置指示器（默认小白点）
                    .setHintColor(getResources().getColor(R.color.colorRed), getResources().getColor(R.color.colorWhite))//设置指示器颜色
                    .setOnPictureLongPressListener(this) // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
                    .setLoader(new ImageWatcher.Loader() {//调用show方法前，请先调用setLoader 给ImageWatcher提供加载图片的实现
                        @Override
                        public void load(Context context, String url, final ImageWatcher.LoadCallback lc) {
                            Glide.with(context).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                    lc.onResourceReady(resource);
                                }

                                @Override
                                public void onLoadStarted(Drawable placeholder) {
                                    lc.onLoadStarted(placeholder);
                                }

                                @Override
                                public void onLoadFailed(Drawable errorDrawable) {
                                    lc.onLoadFailed(errorDrawable);
                                }
                            });
                        }
                    })
                    .create();
            // Utils.fitsSystemWindows(isTranslucentStatus, v_fit);
            commentsAdapter.setData(dataComments);

        }
    }

    private void removeCommentsLoadingItem() {
        if (dataComments.size() > 0) {
            if (dataComments.get(dataComments.size() - 1).getType() == 1) {
                dataComments.remove(dataComments.size() - 1);
            }
        }
    }

    private void addCommentsBaseLine() {
        if (pageNoComments != 1) {
            dataComments.add(new Villages_commentsEntity.BodyEntity.ListEntity(2));
        }
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new Find_House_minsu_listEntity.BodyEntity.ListEntity(2));
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void initView() {

        if (TextUtils.isEmpty(villagesEntity.getBody().getDetail())) {
            rb1.setVisibility(View.GONE);

        }
        if (TextUtils.isEmpty(villagesEntity.getBody().getAround())) {
            rb2.setVisibility(View.GONE);

        }
        if (villagesEntity.getBody().getCommentNum() == 0) {
            rbPL.setVisibility(View.GONE);
        }

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.ic_replace)
                .error(R.drawable.ic_replace)
                .priority(Priority.HIGH)
                .centerCrop();
        Glide.with(this)
                .asBitmap().load(villagesEntity.getBody().getImageURL())
                .apply(options)
                .into(sdv);

        // sdv.setImageURI(villagesEntity.getBody().getImageURL());
        tvTitle.setText(villagesEntity.getBody().getName());
        tvAddr.setText(villagesEntity.getBody().getName());
        tvDes.setText(villagesEntity.getBody().getDescription());
        rbPL.setText("评论（" + villagesEntity.getBody().getCommentNum() + "）");
    }

    @Override
    public void onFailure(String url, String error) {
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
        dismissLoading();
        ToastUtil.initToast(this, "网络错误");
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }

    }

    /**
     * 处理图片视频填充手机宽度
     *
     * @param webView
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void imageFillWidth(WebView webView, String htmlStr) {
        //htmlStr.replace("height: 100%","height: auto");
        Document doc = Jsoup.parse(htmlStr);

        //修改视频标签
        Elements embeds = doc.getElementsByTag("embed");
        for (Element element : embeds) {
            //宽度填充手机，高度自适应
            element.attr("width", "100%").attr("height", "auto");
        }
        //webview 无法正确识别 embed 为视频，所以这里把这个标签改成 video 手机就可以识别了
        doc.select("embed").tagName("video");

        //控制图片的大小
        Elements imgs = doc.getElementsByTag("img");
        for (int i = 0; i < imgs.size(); i++) {
            //宽度填充手机，高度自适应

            String width = imgs.get(i).attr("width");
            if (!TextUtils.isEmpty(width)) {
                int phoneWidth = PhoneUtil.getPhoneWidth(this);

                try {
                    if (Integer.parseInt(width) > PhoneUtil.PixelsToDip(this, phoneWidth)) {
                        imgs.get(i).attr("width", "100%").attr("height", "auto");
                    }
                } catch (Exception e) {
                    continue;
                }


            } else {
                imgs.get(i).attr("style", "width:  100%; height: auto;");

            }
        }
        //控制图片的大小
        Elements video = doc.getElementsByTag("video");
        for (int i = 0; i < video.size(); i++) {
            //宽度填充手机，高度自适应
            video.get(i).attr("style", "width: 100%; height: auto;");
        }

     /*   //控制图片的大小
        Elements section = doc.getElementsByTag("section");
        for (int i = 0; i < section.size(); i++) {
            //宽度填充手机，高度自适应
            section.get(i).attr("style", "width: 100%; height: auto;");
        }*/
        webView.setWebContentsDebuggingEnabled(true);
        //加载使用 jsoup 处理过的 html 文本
        webView.loadDataWithBaseURL(null, doc.toString(), "text/html", "UTF-8", null);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_0: {
                rvDataList.setVisibility(View.VISIBLE);
                linearLayout2.setVisibility(View.VISIBLE);
                rvComments.setVisibility(View.GONE);
                nsv.setVisibility(View.GONE);
            }
            break;
            case R.id.rb_1: {
                rvDataList.setVisibility(View.GONE);
                rvComments.setVisibility(View.GONE);

                nsv.setVisibility(View.VISIBLE);
                linearLayout2.setVisibility(View.GONE);
                tvH5.getSettings().setJavaScriptEnabled(true);
                tvH5.setWebChromeClient(new WebChromeClient());
                imageFillWidth(tvH5, villagesEntity.getBody().getDetail().replace("<p><br></p><p><br></p>", ""));
            }
            break;
            case R.id.rb_2: {
                rvComments.setVisibility(View.GONE);

                rvDataList.setVisibility(View.GONE);

                nsv.setVisibility(View.VISIBLE);
                linearLayout2.setVisibility(View.GONE);
                tvH5.getSettings().setJavaScriptEnabled(true);
                tvH5.setWebChromeClient(new WebChromeClient());
                imageFillWidth(tvH5, villagesEntity.getBody().getAround().replace("<p><br></p><p><br></p>", ""));
            }
            break;
            case R.id.rb_3: {
                rvComments.setVisibility(View.VISIBLE);
                rvDataList.setVisibility(View.GONE);
                linearLayout2.setVisibility(View.GONE);
                nsv.setVisibility(View.GONE);
            }
            break;
        }
    }

    private void initSharePop() {
        mRxManager.on("sharepopEntity", new Consumer<AllPostersEntity.BodyBean>() {

            @Override
            public void accept(AllPostersEntity.BodyBean bodyBean) throws Exception {

                allPostersEntity = bodyBean;
            }
        });
        mRxManager.on("sharepop", new Consumer<ImageWatcher>() {
            @Override
            public void accept(ImageWatcher imageWatcher) throws Exception {
                vImageWatcher = imageWatcher;
                vImageWatcher.setImageWatcherOndismiss(new ImageWatcher.ImageWatcherDiss() {
                    @Override
                    public void onImageWatcherDiss() {
                        if (allPostersEntity!=null){
                            ShareActivityPop sharePop = new ShareActivityPop(BourbonListActivity.this, BourbonListActivity.this, allPostersEntity);
                            sharePop.showPopupWindow();
                        }
                    }
                });
            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tuiguang://推荐
                ////2 小区，3 房源 ，7 酒店，52 特卖(预售)
                ShareUtils.getDataActivity( this, "3",data.get((Integer) view.getTag()).getId()+"");

               /* Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
                intent.putExtra("type", 1);
                intent.putExtra("houseId", data.get((Integer) view.getTag()).getId());
                intent.putExtra("presellProduct", false);

                intent.putExtra("brokerAge", data.get((Integer) view.getTag()).getBrokerAgeAmountValue());
                intent.putExtra("persellId", data.get((Integer) view.getTag()).getId());
                startActivity(intent);*/
               /* loadingDialog = LoadingDialog.newInstance("跳转中");
                loadingDialog.show(getFragmentManager(), "loading");
                String villageId = data.get((Integer) view.getTag()).getId();

                OkHttpUtil.getJSON(this, String.format(Constant.URL.vips_villages_posters, villageId), new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        if (!TextUtils.isEmpty(json)) {
                            dismissLoading();
                            Material_postersEntity material_postersEntity = gson.fromJson(json, Material_postersEntity.class);
                            if ("200".equals(material_postersEntity.getCode())) {
                                LogeUtil.e("material_posters" + json);
                                ErWeiMaDialog erWeiMaDialog = ErWeiMaDialog.newInstance(material_postersEntity.getBody().getPoster());
                                erWeiMaDialog.show(getFragmentManager());

                                erWeiMaDialog.setOnItemClickListener(BourbonListActivity.this);
                            } else {
                                ToastUtil.initToast(BourbonListActivity.this, material_postersEntity.getMsg());
                            }
                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });
*/
                break;
        }

    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getHouseList();
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent = new Intent(this, HouseDetailsActivityFor3.class);
        intent.putExtra("type", 0);
        intent.putExtra("houseId", data.get(position).getId());
        intent.putExtra("presellProduct", false);
        intent.putExtra("brokerAge", data.get(position).getBrokerAgeAmountValue());
        intent.putExtra("persellId", data.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getHouseList();
    }


    @Override
    public void onThumbPictureClick(ImageView i, List<ImageView> imageGroupList, List<String> urlList) {
        vImageWatcher.show(i, imageGroupList, urlList);
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }


    public boolean onBack() {
        if (vImageWatcher == null) {
            return false;
        } else {
            // 当确认没有子Fragmnt时可以直接return false
            if (!vImageWatcher.handleBackPressed()) {
                return BackHandlerHelper.handleBackPress(this);
            } else {
                return !BackHandlerHelper.handleBackPress(this);
            }
        }


    }

    @Override
    public void onBackPressed() {

        if (!onBack()) {
            super.onBackPressed();

        }
    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {

            case R.id.tv_wx: {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(BourbonListActivity.this, 0, images, images.get(images.size() - 1),"");

            }
            break;
            case R.id.tv_pyq: {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getFragmentManager(), "loading");
                List<String> images = new ArrayList<>();
                images.add((String) v.getTag());
                ShareUtilse.shareImage(BourbonListActivity.this, 1, images, images.get(images.size() - 1),"");

            }
            break;
            case R.id.tv_save: {
                saveImageToSdCard(this, (String) v.getTag(), true);
                ToastUtil.initToast(this, "保存成功");
            }
            break;
        }
    }


    //根据网络图片url路径保存到本地
    public static final File saveImageToSdCard(Context context, String image, boolean isxiangce) {
        boolean success = false;
        File file = null;
        try {
            if (isxiangce) {
                file = createXiangCeImageFile(context);
            } else {
                file = createStableImageFile(context);

            }

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            int code = conn.getResponseCode();
            if (code == 200) {
                is = conn.getInputStream(); // 得到网络返回的输入流
            } else {
                is = conn.getErrorStream(); // 得到网络返回的输入流
            }

            //is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    public static String IMAGE_NAME = "iv_share_";
    public static int i = 0;

    //创建相册
    public static File createXiangCeImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + ".jpg";

        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + imageFileName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        i++;
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    //打开小程序
    public void shareXCX() {

        if (villagesEntity != null) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    VillagesEntity.BodyEntity.ShareResponseEntity shareResponse = villagesEntity.getBody().getShareResponse();

                    File file = saveImageToSdCard(BourbonListActivity.this, shareResponse.getImageUrl());

                    String fileName = file.getAbsolutePath();


                    WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
                    miniProgramObj.webpageUrl = shareResponse.getLink(); // 兼容低版本的网页链接
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
                    miniProgramObj.userName = shareResponse.getMiniAppId();     // 小程序原始id
                    miniProgramObj.path = shareResponse.getPath();            //小程序页面路径
                    WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                    msg.title = shareResponse.getTitle();                 // 小程序消息title
                    msg.description = shareResponse.getDesc();
                    Bitmap bitmap = BitMapUtil.getBitmap(fileName);
                    msg.thumbData = BitMapUtil.compressBitmap(bitmap, 100 * 1024);// 小程序消息desc

                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = "webpage";
                    req.message = msg;
                    req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
                    IWXAPI api = WXAPIFactory.createWXAPI(BourbonListActivity.this, Constant.ID.WeChat_APP_ID, false);

                    api.sendReq(req);
                }
            }).start();

        }


    }

    //根据网络图片url路径保存到本地
    public File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {

            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }


}
